package com.ckd.flyingtrip.activity;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.alipay.sdk.app.PayTask;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.AlipayFormBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.PayResult;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/*
 * 支付宝
 * */
public class Alipay {
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private BaseActivity context;
    private String money_fell;
    private AlipayFormBean alipayFormBean;
    private String order_id;

    public Alipay(BaseActivity context, String money_fell) {
        this.context = context;
        this.money_fell = money_fell;
    }


    public void volleyQueryShared(String token) {
        StringRequest request = new StringRequest(Request.Method.GET, Constants.shared_payAli + "?deptId=243", new Response.Listener<String>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(String s) {
                Log.i("调取支付宝", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("message");
                    if (code.equals("200")) {
                        String dataInfo = json.getString("data");
                        Log.i("调取支付宝Data", dataInfo);
                        payV2(dataInfo);
                    } else {
                        Tools.toast(msg);
                        context.dismisProgressDialog();
                    }
                } catch (JSONException e) {
                    context.dismisProgressDialog();
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                context.dismisProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> mHeader = new HashMap<String, String>();
                mHeader.put("TOKEN_XCX_SHARE", token);
                return mHeader;
            }
        };
        SingleVolleyRequestQueue.getInstance(context).addToRequestQueue(request);
    }

    /*缴费套餐支付*/
    public void volleyQueryJiaofei(String costId, String number, boolean b) {
        Gson gson = new Gson();
        StringRequest request = new StringRequest(Request.Method.POST, Constants.DIAOYONGZHIFUBAO, new Response.Listener<String>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(String s) {
                Log.i("调取支付宝", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        String dataInfo = json.getString("data");

                        Log.i("调取支付宝Data", dataInfo);
//                        String type = dataInfo.getString("type");
                        alipayFormBean = gson.fromJson(dataInfo, AlipayFormBean.class);
                        Log.i("调取支付宝Mod", alipayFormBean.toString());
                        String currency_type = alipayFormBean.getCurrency_type();
                        String appid = alipayFormBean.getApp_id();
                        order_id = alipayFormBean.getOrder_id();
//                        if (!Tools.isEmpeyNull(appid)
//                                || !Tools.isEmpeyNull(order_id)
//                                || !Tools.isEmpeyNull(currency_type)
//                        ) {
//                            Toast.makeText(context,"支付失败，请重试",Toast.LENGTH_SHORT).show();
//                        } else {
                        payV2(currency_type);
//                        }
                    } else {
                        Tools.toast(msg);
                        context.dismisProgressDialog();
                    }
                } catch (JSONException e) {
                    context.dismisProgressDialog();
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                context.dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("payWay", "03");
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("costId", costId);
                    if (b)
                        json_url.put("number", number);
                    else
                        json_url.put("number", "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                Log.i("获取支付宝传值", json_url.toString());
                return map;
            }
        };
//        request.setRetryPolicy(new DefaultRetryPolicy(60000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        SingleVolleyRequestQueue.getInstance(context).addToRequestQueue(request);
    }


    /*
     * 买车
     * */
    public void volleyQueryZhifu(String costId) {
        Gson gson = new Gson();
        String url = Constants.MAICHE;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(String s) {
                Log.i("调取支付宝", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        String dataInfo = json.getString("data");

                        Log.i("调取支付宝Data", dataInfo);
//                        String type = dataInfo.getString("type");
                        alipayFormBean = gson.fromJson(dataInfo, AlipayFormBean.class);
                        Log.i("调取支付宝Mod", alipayFormBean.toString());
                        String currency_type = alipayFormBean.getCurrency_type();
                        String appid = alipayFormBean.getApp_id();
                        order_id = alipayFormBean.getOrder_id();
//                        if (!Tools.isEmpeyNull(appid)
//                                || !Tools.isEmpeyNull(order_id)
//                                || !Tools.isEmpeyNull(currency_type)
//                        ) {
//                            Toast.makeText(context,"支付失败，请重试",Toast.LENGTH_SHORT).show();
//                        } else {
                        payV2(currency_type);
//                        }
                    } else {
                        Tools.toast(msg);
                        context.dismisProgressDialog();
                    }
                } catch (JSONException e) {
                    context.dismisProgressDialog();
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                context.dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("payWay", "03");
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("bicycleId", costId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                Log.i("获取支付宝传值", json_url.toString());
                return map;
            }
        };
//        request.setRetryPolicy(new DefaultRetryPolicy(60000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        SingleVolleyRequestQueue.getInstance(context).addToRequestQueue(request);
    }


    /*
     * 租车交押金
     * */
    public void volleyQueryzuche(String costId, String type) {
        Gson gson = new Gson();
        String url = Constants.ZHUCHE;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(String s) {
                Log.i("调取支付宝", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        String dataInfo = json.getString("data");

                        Log.i("调取支付宝Data", dataInfo);
//                        String type = dataInfo.getString("type");
                        alipayFormBean = gson.fromJson(dataInfo, AlipayFormBean.class);
                        Log.i("调取支付宝Mod", alipayFormBean.toString());
                        String currency_type = alipayFormBean.getCurrency_type();
                        String appid = alipayFormBean.getApp_id();
                        order_id = alipayFormBean.getOrder_id();
//                        if (!Tools.isEmpeyNull(appid)
//                                || !Tools.isEmpeyNull(order_id)
//                                || !Tools.isEmpeyNull(currency_type)
//                        ) {
//                            Toast.makeText(context,"支付失败，请重试",Toast.LENGTH_SHORT).show();
//                        } else {
                        payV2(currency_type);
//                        }
                    } else {
                        Tools.toast(msg);
                        context.dismisProgressDialog();
                    }
                } catch (JSONException e) {
                    context.dismisProgressDialog();
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                context.dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("payWay", "03");
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("bicycleId", costId);
                    json_url.put("payType", type);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                Log.i("获取支付宝传值", json_url.toString());
                return map;
            }
        };
//        request.setRetryPolicy(new DefaultRetryPolicy(60000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        SingleVolleyRequestQueue.getInstance(context).addToRequestQueue(request);
    }


    /**
     * 支付宝支付业务示例
     */
    public void payV2(final String orderInfo) {
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(context);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            Log.e("支付宝回调", msg.what + "");
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    context.dismisProgressDialog();

                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);

                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
//                    @SuppressWarnings("unchecked")
//                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
//                    String resultStatus = authResult.getResultStatus();
//
//                    // 判断resultStatus 为“9000”且result_code
//                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
//                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
//                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
//                        // 传入，则支付账户为该授权账户
////                        showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
//                    } else {
//                        // 其他状态值则为授权失败
////                        showAlert(PayDemoActivity.this, getString(R.string.auth_failed) + authResult);
//                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };
}
